<?php


namespace app\common\service;


use app\common\model\MemberRoles;
use app\common\model\PointsLog;

class PointsService
{
    //添加积分记录                       会员id     积分 状态 0未通过 1通过 用户id  类型     备注
    public function SaveMemberPoints($member_id,$points,$status,$user_id = 0,$type = 0,$remarks = ''){
        PointsLog::create([
            "member_id" => $member_id,
            "points" => $points,
            "type" => $type,
            "status" => $status,
            "user_id" => $user_id,
            "remarks" => $remarks
        ]);
        return true;
    }
    //重算用户积分
    public function RecalculationMemberPoints($member_id){
        //获取用户积分
        $points = PointsLog::where("member_id",$member_id)->where("status",1)->sum('points');
        //更新用户积分
        \app\common\model\Members::where("id",$member_id)->update([
            'points' => $points
        ]);
        return true;
    }
    //重算用户总积分
    public function RecalculationMemberTotalPoints($member_id){
        //获取用户积分
        $points = PointsLog::where("member_id",$member_id)->where("status",1)->where("type",0)->sum('points');
        //更新用户积分
        \app\common\model\Members::where("id",$member_id)->update([
            'total_points' => $points
        ]);
        return true;
    }
    //重置会员角色
    public function ResetMemberRole($member_id){
        //获取会员总积分
        $total_points = \app\common\model\Members::where("id",$member_id)->value('total_points');
        //获取会员角色
        $role_id = MemberRoles::where("demand_integral","<=",$total_points)->order("demand_integral desc")->value('id');
        $role_id = $role_id ? $role_id : 0;
        //更新用户角色
        \app\common\model\Members::where("id",$member_id)->update([
            'role_id' => $role_id
        ]);
        return true;
    }
}